<?php
namespace Commnet\Model;
use PhalApi\Model\DataModel;

class Commnet extends DataModel {

    protected function getTableName($id) {
        return 'commnet';
    }

    public function insertCommnet($data) {
        return $this->getORM()->insert($data);
    }

    /**
        增加评论
    */
    public function addCommnet($data) {
        $model = new CommnetCategory();
        $info = $this->getORM()->select('*')
            ->where(
                array(
                    'title' => $data['title'],
                    'content' => $data['content'],
                )
            )->fetchOne();
        if ( $info ){
            return $model->checkName($data['name']);
        }


        $list =  $model->addCategory($data['name']);
        $insert = array(
            'title' =>  $data['title'],
            'content' =>  $data['content'],
            'name' =>  $data['name'],
            'name_id' =>  $list['id'],
            'count' =>  $list['count']+1,
            'update_time' =>  date('Y-m-d H:i:s',time()),
            'create_time' =>  date('Y-m-d H:i:s',time()),
        );
        return $this->insertCommnet($insert);
    }

    public function getCommnet($name){
        $KeyName = $name.'_cKey';
        $KeyName_max = $name.'_max';
        // 获取，输出：2015
        $KeyName_mun = \PhalApi\DI()->cache->get( $KeyName );
        if ( !$KeyName_mun  ){
            \PhalApi\DI()->cache->set( $KeyName,1,365*24*60*60 );
            $KeyName_mun = 1;
        }


        $count = \PhalApi\DI()->cache->get( $KeyName_max );

        if ( !$count ){
            $model = new CommnetCategory();
            $category = $model->checkName($name);
            $count = $category['count'];
            \PhalApi\DI()->cache->set( $KeyName_max,$count );
        }

        $commnet = $this->getORM()->select('*')->where(array('name'=>$name,"count"=>$KeyName_mun))->fetchOne();

        if ( $KeyName_mun < $count ){
            \PhalApi\DI()->cache->set( $KeyName,$KeyName_mun+1,365*24*60*60 );
        }else{
            \PhalApi\DI()->cache->set( $KeyName,1,365*24*60*60 );
        }

        return $commnet;
    }

}
